#!/bin/bash

# Feng Admin 后端服务启动脚本 (Linux/macOS)

# 颜色定义
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Feng Admin - 后端服务${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# 获取Python命令
if command -v python3 &> /dev/null; then
    PYTHON_CMD="python3"
elif command -v python &> /dev/null; then
    PYTHON_CMD="python"
else
    echo -e "${RED}错误: 未找到 Python${NC}"
    exit 1
fi

# 检查虚拟环境
if [ ! -d "../../.venv" ]; then
    echo -e "${YELLOW}虚拟环境不存在，正在创建...${NC}"
    $PYTHON_CMD -m venv ../../.venv
    echo -e "${GREEN}✓ 虚拟环境创建成功${NC}"
    echo ""
fi

# 激活虚拟环境
echo -e "${BLUE}正在激活虚拟环境...${NC}"
source ../../.venv/bin/activate

# 检查依赖
echo -e "${BLUE}正在检查依赖...${NC}"
if [ ! -f "../../.venv/.deps_installed" ]; then
    echo -e "${YELLOW}首次运行，正在安装依赖...${NC}"
    pip install -r requirements.txt
    touch ../../.venv/.deps_installed
    echo -e "${GREEN}✓ 依赖安装完成${NC}"
else
    echo -e "${GREEN}✓ 依赖已安装${NC}"
fi

echo ""

# 检查数据库
if [ ! -f "instance/feng_admin.db" ]; then
    echo -e "${YELLOW}数据库不存在，正在初始化...${NC}"
    $PYTHON_CMD scripts/init_db.py
    echo -e "${GREEN}✓ 数据库初始化完成${NC}"
    echo ""
fi

# 读取端口配置
BACKEND_PORT=5001
if [ -f ".env" ]; then
    PORT=$(grep "^FLASK_PORT=" .env | cut -d'=' -f2)
    BACKEND_PORT=${PORT:-5001}
fi

# 启动服务
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  启动后端服务...${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "后端地址: ${BLUE}http://localhost:${BACKEND_PORT}${NC}"
echo -e "API文档: ${BLUE}http://localhost:${BACKEND_PORT}/api${NC}"
echo ""
echo -e "${YELLOW}按 Ctrl+C 停止服务${NC}"
echo ""

# 清理函数
cleanup() {
    echo ""
    echo -e "${YELLOW}正在停止后端服务...${NC}"
    # 获取端口号（已在前面读取）
    # 强制杀死占用端口的进程
    lsof -ti:${BACKEND_PORT} 2>/dev/null | xargs kill -9 2>/dev/null
    echo -e "${GREEN}后端服务已停止${NC}"
    exit 0
}

# 设置信号处理
trap cleanup INT TERM

# 启动Flask应用
$PYTHON_CMD app.py

